package com.starblink.android.basic.sensorsdata.spm.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.starblink.android.basic.ext.toJson
import com.starblink.android.basic.sensorsdata.room.mana.SkTraceDatabaseManager
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.basic.util.log.YYLogUtils
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit


class SpmUploadService : Service() {

    companion object {
        const val TAG = "SpmUploadService"
    }

//    private lateinit var tt: TimeSpmTask<TimeSpmTask.Task>


    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        YYLogUtils.i(TAG, "spm 上报服务 onCreate")
        super.onCreate()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        YYLogUtils.i(TAG, "Spm 上报服务 onStartCommand");
        val service: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
        // 创建一个Runnable对象
        val task = Runnable { // 执行某个任务
            YYLogUtils.i(TAG, "Spm  执行上报....")
            uploadSpmData()
        }
        // 设置在5秒后开始执行，并且每隔10秒重复执行一次
        service.scheduleAtFixedRate(task, 0, 5, TimeUnit.SECONDS)
        return super.onStartCommand(intent, flags, startId)
    }


    override fun onDestroy() {
        YYLogUtils.i(TAG, "Spm 上报服务 onDestroy")
        super.onDestroy()
    }

    private fun uploadSpmData() {
        GlobalScope.async {
            try {
                SkTraceDatabaseManager.db.skTraceDao.queryOne()?.let {
                    SpmTrackHandler.upload(it, uploadSuccess = {
                        YYLogUtils.i(TAG, "spm---> 埋点上报成功 ---> 捕获一个 ${it.spmCnt}")
                        SkTraceDatabaseManager.db.skTraceDao.delete(it)
//                            async {//测试用
//                                SkTraceDatabaseManager.db.skTraceDao.queryItems().let { items ->
//                                    YYLogUtils.i(
//                                        TAG,
//                                        "spm---> 埋点上报成功 ---> 剩余条数 ${items?.size}"
//                                    )
//                                }
//                            }
                    }, uploadFail = {

                    })
                }
            } catch (e: Exception) {
                YYLogUtils.i(TAG, "Spm 上报服务 上报出错！！！！！！！！！！！！！！！！！！！！！！！！！！！")
            }
        }
    }


}